<template>
  <!-- 公告管理 公告列表 -->
  <div class="announcementManagement">
    <el-card class="list-box">
      <div slot="header" class="table_header">
        <span>公告列表</span>
        <div>
          <router-link :to="'/announcementManagement/addNotice'">
            <el-button size="small" type="primary">新增公告</el-button>
          </router-link>

          <el-button icon="el-icon-refresh-right" circle @click="handleRefresh" />
        </div>
      </div>
      <div class="list-container">
        <el-table :data="tableData" border show-overflow-tooltip stripe style="width: 100%">
          <el-table-column
            v-for="(column,index) in columns"
            :key="index"
            :prop="column.prop"
            :label="column.lable"
            show-overflow-tooltip
            :width="column.width || ''"
          >
            <template slot-scope="scope">

              <span v-if="column.prop === 'isTop'">
                {{ setIsTop(scope.row.isTop) }}
              </span>

              <el-switch
                v-else-if="column.prop === 'isStatus'"
                class="statusSwitchStyle"
                :value="scope.row.isStatus"
                :active-value="1"
                :inactive-value="0"
                active-text=""
                active-color="#42b983"
                @change="handleStatusChange(scope.row.id ,$event)"
              />
              <span v-else>
                {{ formatter(scope.row,column.prop) ||'--' }}
              </span>

            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :width="150" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="lookItem(scope)">查看</el-button>
              <el-button type="text" size="small" @click="editItem(scope)">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog title="查看公告" :visible.sync="dialogFormVisible" width="80%">
        <div>
          <el-form ref="ruleForm" :model="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="公告名称">
              <el-input v-model="ruleForm.title" style="width: 25%;" disabled />
            </el-form-item>
            <el-form-item label="正文">
              <!-- 图片上传组件辅助 -->
              <el-upload
                disabled
                class="avatar-uploader"
                :action="editorOption.serverUrl"
                name="file"
                :headers="editorOption.headerObj"
                :auto-upload="true"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :before-upload="beforeUpload"
                style="display: none;"
              />
              <quill-editor
                ref="myQuillEditor"
                v-model.lazy.trim="ruleForm.content"
                disabled
                class="editor"
                :options="editorOption"
                @focus="onEditorFocus($event)"
              />

            </el-form-item>
            <el-form-item label="分类">
              <el-select
                v-model="ruleForm.classification"
                multiple
                clearable
                filterable
                placeholder="请选择"
                style="width: 25%;"
                disabled
              >
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否置顶">
              <el-switch
                v-model="ruleForm.isTop"
                disabled
                active-color="#42b983"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange"
              />
            </el-form-item>
          </el-form>

        </div>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
        </div>
      </el-dialog>

      <pagination
        v-if="totalPages>0"
        :total="totalPages"
        :page.sync="listQuery.pageNumber"
        :limit.sync="listQuery.pageSize"
        :layout="pageLayout"
        @pagination="handlePageClick"
      />
    </el-card>

  </div>
</template>

<script>
  import Pagination from '@/components/Pagination'
  import {
    quillEditor
  } from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import '@/assets/quill.scss'
  import {
    getToken
  } from '@/utils/auth'
  export default {
    components: {
      Pagination,
      quillEditor
    },
    data() {
      const toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'], // toggled buttons
        [{
          'header': 1
        }, {
          'header': 2
        }], // custom button values
        [{
          'list': 'ordered'
        }, {
          'list': 'bullet'
        }],
        [{
          'indent': '-1'
        }, {
          'indent': '+1'
        }], // outdent/indent
        [{
          'direction': 'rtl'
        }], // text direction
        [{
          'size': ['small', false, 'large', 'huge']
        }], // custom dropdown
        [{
          'header': [1, 2, 3, 4, 5, 6, false]
        }],
        [{
          'color': []
        }, {
          'background': []
        }], // dropdown with defaults from theme
        [{
          'font': []
        }],
        [{
          'align': []
        }],
        ['link', 'image'],
        ['clean']
      ]
      return {
        dialogFormVisible: false,
        loading: '',
        // 富文本配置
        editorOption: {
          placeholder: '请输入相关内容',
          modules: {
            toolbar: {
              container: toolbarOptions,
              handlers: {
                'image': function(value) {
                  if (value) {
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false)
                  }
                }
              }
            }
          },
          // 此项配置是选择图片之后的上传路径
          serverUrl: `${process.env.VUE_APP_BEG_IP}xboot/upload/file`,
          headerObj: {
            accessToken: getToken()
          }
        },

        ruleForm: {
          title: '',
          content: '', // 正文
          isTop: 1, // 是否置顶
          classification: [] // 分类

        },

        totalPages: 10,
        listQuery: {
          pageNumber: 1,
          pageSize: 10
        },
        pageLayout: 'total, prev, pager, next, jumper',
        tableData: [],
        columns: [{
            lable: 'ID',
            show: true,
            prop: 'id',
            width: 200
          },
          {
            lable: '当前排序',
            show: true,
            prop: 'serialNumber',
            width: 200
          },
          {
            lable: '标题',
            show: true,
            prop: 'title',
            width: 300
          },
          {
            lable: '分类',
            show: true,
            prop: 'classificationValue',
            width: 300
          },
          {
            lable: '置顶',
            show: true,
            prop: 'isTop',
            width: 100
          },
          {
            lable: '创建时间',
            show: true,
            prop: 'createTime'
          },
          {
            lable: '创建人',
            show: true,
            prop: 'createBy'
          },
          {
            lable: '状态',
            show: true,
            prop: 'isStatus',
            width: 150
          }

        ],
        options: [{
            value: '0',
            label: '首页'
          },
          {
            value: '1',
            label: '车间'
          },
          {
            value: '2',
            label: '安全'
          },
          {
            value: '3',
            label: '质量'
          },
          {
            value: '4',
            label: '电气'
          },
          {
            value: '5',
            label: '质量'
          }
        ]
      }
    },
    computed: {
      setIsTop() {
        return function(st) {
          if (st === 0) {
            return '否'
          } else {
            return '是'
          }
        }
      }

    },
    created() {
      const params = {
        current: this.listQuery.current,
        size: this.listQuery.size
      }
      this.getLists(params)
    },
    methods: {
      formatter(row, prop) {
        const value = row[prop]
        return value
      },
      onEditorFocus(val, quill) {
        quill.enable(false) // 在获取焦点的时候禁用
      },
      beforeUpload(file) {
        this.loading = this.$loading({
          lock: true,
          text: '图片加载中，请稍后！',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      },

      // 上传成功
      uploadSuccess(res, file) {
        // 获取富文本组件实例
        const quill = this.$refs.myQuillEditor.quill
        if (res.code === 200) {
          // 获取光标所在位置
          const length = quill.getSelection().index
          // 获取光标所在位置// 获取光标所在位置
          quill.insertEmbed(length, 'image', res.message)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$message.error(res.message)
        }
        this.loading.close()
      },
      // 上传失败来到这里
      uploadError() {
        this.loading.close()
        this.$message.error('上传失败!')
      },

      // 查看
     async lookItem(scope) {
        try {
          const res = await this.$Http.editAnnouncement({ id: scope.row.id })
           if (res.code === 200) {
             this.ruleForm.content = res.result.content
             this.ruleForm.title = res.result.title
             this.ruleForm.isTop = res.result.isTop
             this.ruleForm.classification = res.result.classification.split(',')
             this.dialogFormVisible = true
           } else {
             this.$message({
               type: 'error',
               message: res.message
             })
           }
        } catch (err) {
          console.log('err', err)
        }
      },
      // 编辑
      editItem(scope) {
        this.$router.push({
          path: '/announcementManagement/editNotice',
          query: {
            id: scope.row.id

          }
        })
      },
      // 上架下架
      handleStatusChange(id, e) {
        const { confirmChangeStatus } = this
        const msg = `确定改变这条记录的状态吗？`
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          confirmChangeStatus(id, e)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          })
        })
      },
      // 修改状态
      async confirmChangeStatus(id, e) {
        try {
          const params = {
            id: id,
            isStatus: e
          }
          const res = await this.$Http.addAnnouncement(params)
          console.log('res', res)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message
            })
            const params = {
              current: this.listQuery.current,
              size: this.listQuery.size
            }
            this.getLists(params)
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } catch (err) {
          this.$message({
            type: 'error',
            message: err
          })
        }
      },
     async getLists(params) {
       try {
         const res = await this.$Http.getAnnouncementList(params)
          if (res.code === 200) {
            this.tableData = res.result.resultData
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
       } catch (err) {
         console.log('err', err)
       }
      },
      handlePageClick() {
        const params = {
          current: this.listQuery.current,
          size: this.listQuery.size
        }
        this.getLists(params)
      },
      handleRefresh() {
        const params = {
          current: this.listQuery.current,
          size: this.listQuery.size
        }
        this.getLists(params)
      },
      // 删除公告
      handleDelete({
        row,
        $index
      }) {
        const {
          id
        } = row

        const msg = `确定删除这条公告吗？删除后可能无法恢复`
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 确定删除
          this.$Http.delAnnouncement({ id: id }).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.message
              })
              const params = {
                current: this.listQuery.current,
                size: this.listQuery.size
              }
              this.getLists(params)
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          }).catch(err => {

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }

    }
  }
</script>

<style lang="scss" scoped>
  .announcementManagement {
    padding: 10px 10px 0 10px;

    .list-box {
      margin-top: 10px;

      .table_header {
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
</style>
